import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

// Nikolas Wolfe
// 2/25/09
// CNT 4007
// Program 1: Client-Server

public class Client
{
	// default settings
	private static String hostname = "sand.cise.ufl.edu";
	private static int port = 6336;
	
	public static void main(String args[]) throws IOException
	{
		// sentence or operation
		String inputData, outputData;
		
		// establish input stream from keyboard
		InputStreamReader input = new InputStreamReader(System.in);
		BufferedReader userInput = new BufferedReader(input);
		
		try 
		{
			hostname = args[0];
			port = Integer.parseInt(args[1]);
			StringBuilder s = new StringBuilder();
			for (int i = 2; i < args.length; ++i)
			{
				s.append(args[i] + " ");
			}
			inputData = s.toString() + "\n";
		} catch ( Exception e )
		{
			System.out.println("Incorrect argument input!\n");
			System.out.print("Enter data: ");
			inputData = userInput.readLine(); // must use carriage return
		}
		
		// establish TCP socket, input, output
		try 
		{
			System.out.print("\nConnecting to server... ");
			Socket clientSocket = new Socket(hostname, port);
			DataOutputStream outputToServer = new DataOutputStream(
					clientSocket.getOutputStream());
			BufferedReader inputFromServer = new BufferedReader(
					new InputStreamReader(clientSocket.getInputStream()));
			System.out.println("Done!\n");
			
			// send message to server once TCP connection is established
			outputToServer.writeBytes(inputData + '\n'); // must use carriage return
			
			// seceive a message from the server
			outputData = inputFromServer.readLine();
			
			// output to the screen
			System.out.println("Response from server: " + outputData);
			
			// close the socket
			clientSocket.close();
		}
		catch( Exception e ) // IOException or UnknownHostException
		{
			System.out.println("Connection failed!\n");
			e.printStackTrace();
		}
	}
}
